// 统一HTTP请求封装
import config from './config.js'

// 创建请求实例
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 显示加载动画
    if (options.loading !== false) {
      uni.showLoading({
        title: '加载中...',
        mask: options.mask || false
      })
    }
    
    // 构建请求参数
    const requestOptions = {
      url: `${config.baseUrl}${options.url}`,
      method: options.method || 'GET',
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      data: options.data || {},
      timeout: config.timeout,
      success: (res) => {
          //console.log("请求状态码",res)
        if (res.statusCode === 200) {
          // 统一处理返回数据格式
          if (res.data.code === 200) {
              console.log("请求成功",res.data.data)
            resolve(res.data)
          } else {
            // 业务错误处理
            uni.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else {
          // HTTP错误处理
          uni.showModal({
            title: '请求错误',
            content: `错误码：${res.statusCode}\n${res.data?.message || '网络请求失败'}`,
            showCancel: false
          })
          reject(res)
        }
      },
      fail: (err) => {
        // 网络错误处理
        uni.showModal({
          title: '网络错误',
          content: err.errMsg || '无法连接到服务器',
          showCancel: false
        })
        reject(err)
      },
      complete: () => {
        // 隐藏加载动画
        if (options.loading !== false) {
          uni.hideLoading()
        }
      }
    }
    
    // 添加token
    const token = uni.getStorageSync('uni_id_token')
    if (token) {
      requestOptions.header['Authorization'] = `Bearer ${token}`
    }
    
    // 发送请求
    uni.request(requestOptions)
  })
}

// 封装GET请求
export const get = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data,
    ...options
  })
}

// 封装POST请求
export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

// 封装PUT请求
export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

// 封装DELETE请求
export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

// 替代uniCloud.callFunction的方法
export const callFunction = (options) => {
  // 显示加载动画（如果需要）
  const showLoading = options.loading !== false
  if (showLoading) {
    uni.showLoading({
      title: '加载中...',
      mask: options.mask || false
    })
  }

  // 从配置中获取对应的API路径
  const apiPath = config.apiPaths[options.name]?.[options.data?.action || options.data?.name]
  
  if (!apiPath) {
    // 在reject前确保隐藏加载动画
    if (showLoading) {
      uni.hideLoading()
    }
    return Promise.reject(new Error(`未找到对应的API路径: ${options.name}.${options.data?.action || options.data?.name}`))
  }
  
  // 构建请求数据
  const requestData = options.data?.data || options.data
  
  // 禁用post方法内部的loading，因为我们在这里统一管理
  return post(apiPath, requestData, {
    loading: false
  }).finally(() => {
    // 确保无论请求成功还是失败，loading都会被隐藏
    if (showLoading) {
      uni.hideLoading()
    }
  })
}

export default {
  request,
  get,
  post,
  put,
  delete: del,
  callFunction
}